package rabbitmq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
import rabbitmq.model.User;

/**
 * 消息生成者
 * Virtual Hosts queue
 * 一个用户可以对应多个Virtual Hosts，一个Virtual Hosts可以创建多个queue，过个Virtual Hosts之间相互独立
 * @RunWith(SpringJUnit4ClassRunner.class) 为加载spring
 * @ContextConfiguration(locations = {"classpath:spring/spring-database.xml"})
 * 单元测试
 */

public class Producer3  {

	Connection connection = null;
	Channel channel = null;
	ConnectionService connectionService = null;

	@Test
	public void test1(){
		connectionService = new ConnectionService();
		try {
			//创建与RabbitMQ服务器的TCP连接
			connection  = connectionService.initConn();
			channel = connection.createChannel();

			/**
			 * 声明队列，如果队列已存在，则直接写入,如队列不存在则会创建队列
			 * 如QUEUE_NAME是一个transient的queue，第二个参数必须是false；重启rabbit后QUEUE_NAME会被删除掉
			 * 如QUEUE_NAME是一个durability的queue，第二个参数必须是true；重启rabbit后QUEUE_NAME不会被删除掉
			 */
			channel.queueDeclare("1Queue", true, false, false, null);
			String message ;

			long startTime = System.currentTimeMillis();
			for (int i = 0; i <1000 ; i++) {
				User user = new User();
				user.setId(i+1);
				user.setName("Hubert"+(i+1));
				user.setSex(i+1);
				user.setTel("111222333");
				message = JSON.toJSONString(user);
				/**
				 * 默认exchange，类型为direct,默认routingKey与queue相同；
				 * 因为与默认exchange绑定，所以就算绑定其他类型的exchange，用此默认exchange也可以写入。
				 */
				//不保存消息，重启rabbit后待消费的消息都将丢失,routingkey
				channel.basicPublish("", "", null, (message+i).getBytes());
				System.out.println(" Consumer have received '" + message + "'");

				//将消息保存起来，重启rabbit后待消费的消息不会被删除
				//channel.basicPublish("", "firstQueue", MessageProperties.PERSISTENT_TEXT_PLAIN, (message+i).getBytes());
			}
			System.out.println(System.currentTimeMillis() - startTime);
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if(channel != null) {
					channel.close();
				}
				if(connection != null) {
					connection.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	@Test
	public void test2() {
		System.out.println("junit2");
	}
}
